<?php

use \LeanCloud\Engine\Cloud;

// 定义读取 rankings.json 文件内容的云函数
Cloud::define("getRankings", function($params, $user) {
    $filePath = __DIR__ . '/../src/rankings.json';  // 文件路径，确保与保存时的路径一致

    // 检查文件是否存在
    if (!file_exists($filePath)) {
        return [
            "error" => true,
            "message" => "The rankings file does not exist."
        ];
    }

    // 读取文件内容
    $jsonContent = file_get_contents($filePath);
    $rankings = json_decode($jsonContent, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            "error" => true,
            "message" => "Failed to decode rankings JSON."
        ];
    }

    return [
        "error" => false,
        "rankings" => $rankings
    ];
});

Cloud::define("updateAllRankings", function($params, $user) {
    // 固定的配置信息
    $host = "0nbbftcb.cloud.tds1.tapapis.cn";  // 云函数访问的 host
    $clientId = "0nbbftcbjdxoukznct";  // 客户端 ID，已更新
    $clientToken = "YY0YDQxWuNvCOr5kyTZdesnTh27fR6mFJ72aPxZX";  // 客户端 Token，已更新

    $rankNames = [
        "Day_1_15", "Day_16", "Day_17", "Day_18", "Day_19",
        "Day_20", "Day_21", "Day_22", "Day_23", "Day_24",
        "Day_25", "Day_26", "Day_27", "Day_28", "Day_29",
        "Day_30", "Day_31"
    ];

    $baseVersions = [
        22, 87, 87, 87, 87,
        87, 87, 87, 87, 87,
        87, 87, 87, 87, 87,
        87, 87
    ];

    // 计算从2024年11月10日起至今的天数
    $start_date = new DateTime('2024-11-09');
    $today_date = new DateTime();
    $interval = $start_date->diff($today_date);
    $days_passed = $interval->days;

    // 更新版本号，每过一天增加1
    $updatedVersions = array_map(function($version) use ($days_passed) {
        return $version + $days_passed;
    }, $baseVersions);

    $rankings = [];

    foreach ($rankNames as $index => $statisticName) {
        $version = $updatedVersions[$index];
        $url = "https://$host/1.1/leaderboard/leaderboards/user/$statisticName/ranks?count=1&version=$version";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 8);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "X-LC-Id: $clientId",
            "X-LC-Key: $clientToken"
        ));

        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            continue; // 跳过请求失败的排行榜
        }

        $parsedJson = json_decode($response, true);
        if (json_last_error() === JSON_ERROR_NONE && isset($parsedJson['count'])) {
            $rankings[$statisticName] = $parsedJson['count'];
        }
    }

    // 将排行榜信息保存到 JSON 文件
    $filePath = __DIR__ . '/../src/rankings.json';  // 注意路径是否正确
    if (!file_put_contents($filePath, json_encode($rankings, JSON_PRETTY_PRINT))) {
        throw new Exception("Failed to write rankings to file.");
    }

    return $rankings;
});


Cloud::define("timestamp", function($params, $user) {
    $t  = microtime(true);
    $t1 = intval($t);
    $t2 = intval(($t - $t1) * 1000);
    $t3 = $t1 * 1000 + $t2;
    $arr = [
        "ret_code"  => 0,
        "time_str"  => date('Y-m-d H:i:s', $t1) . "." . $t2,
        "remark"    => "",
        "time_long" => $t3,
    ];
    return $arr;
});
// /1.1/functions/sayHello
Cloud::define("sayHello", function($params, $user) {
    return "hello {$params['name']}";
});

// /1.1/functions/sieveOfPrimes
Cloud::define("sieveOfPrimes", function($params, $user) {
    $n = isset($params["n"]) ? $params["n"] : 1000;
    error_log("Find prime numbers less than {$n}");
    $primeMarks = array();
    for ($i = 0; $i <= $n; $i++) {
        $primeMarks[$i] = true;
    }
    $primeMarks[0] = false;
    $primeMarks[1] = false;

    $x = round(sqrt($n));
    for ($i = 2; $i <= $x; $i++) {
        if ($primeMarks[$i]) {
            for ($j = $i * $i; $j <= $n;  $j = $j + $i) {
                $primeMarks[$j] = false;
            }
        }
    }

    $numbers = array();
    forEach($primeMarks as $i => $mark) {
        if ($mark) {
            $numbers[] = $i;
        }
    }
    return $numbers;
});

/*

Cloud::onLogin(function($user) {
    // reject blocker user for login
    if ($user->get("isBlocked")) {
        throw new FunctionError("User is blocked!", 123);
    }
});

Cloud::onInsight(function($params) {
    return;
});

Cloud::onVerified("sms", function($user){
    return;
});

Cloud::beforeSave("TestObject", function($obj, $user) {
    return $obj;
});

Cloud::beforeUpdate("TestObject", function($obj, $user) {
    // $obj->updatedKeys is an array of keys that is changed in the request
    return $obj;
});

Cloud::afterSave("TestObject", function($obj, $user, $meta) {
    // function can accepts optional 3rd argument $meta, which for example
    // has "remoteAddress" of client.
    return ;
});

*/
